import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Input,
  Select,
  Modal,
  Form,
  message,
  Tooltip,
  Popconfirm,
  Badge,
  Typography,
  Row,
  Col,
  Statistic,
  Progress,
  DatePicker,
  Descriptions,
  Divider,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  UserOutlined,
  LockOutlined,
  UnlockOutlined,
  CrownOutlined,
  SafetyCertificateOutlined,
  TeamOutlined,
  RiseOutlined,
  BarChartOutlined,
  UsergroupAddOutlined,
  SafetyOutlined,
  UserSwitchOutlined,
  UserDeleteOutlined,
  PhoneOutlined,
  MailOutlined,
  ClockCircleOutlined,
  CalendarOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { PlatformUser } from '../../types/platform';
import { usePlatformUsers, type PlatformUserFormData } from '../../hooks/business';
import { usePlatformPermission } from '../../hooks/platform/usePlatformPermission';
import { platformUsersApi } from '../../services/platform/api/platformUsersApi';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;
const { Text, Title } = Typography;
const { RangePicker } = DatePicker;

const PlatformUsersPage: React.FC = () => {
  const { checkAnyPermission } = usePlatformPermission();
  
  // 使用业务hooks管理状态
  const {
    users,
    loading,
    pagination,
    availableRoles,
    searchText,
    statusFilter,
    createUser,
    updateUser,
    deleteUser,
    toggleUserStatus,
    resetUserPassword,
    handleSearch,
    handleStatusFilter,
    handlePageChange,
    refresh,
  } = usePlatformUsers();

  // 本地UI状态
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState<PlatformUser | null>(null);
  const [viewingUser, setViewingUser] = useState<PlatformUser | null>(null);
  const [form] = Form.useForm();

  // 处理用户操作
  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (user: PlatformUser) => {
    setEditingUser(user);
    form.setFieldsValue({
      ...user,
      platformRoles: user.platformRoles || [],
    });
    setModalVisible(true);
  };

  const handleView = (user: PlatformUser) => {
    setViewingUser(user);
    setDetailModalVisible(true);
  };

  const handleDelete = async (userIds: string[]) => {
    try {
      await deleteUser(userIds);
    } catch (error) {
      console.error('Delete user error:', error);
    }
  };

  const handleStatusToggle = async (userId: string, status: 'active' | 'inactive' | 'locked') => {
    try {
      await toggleUserStatus(userId, status);
    } catch (error) {
      console.error('Toggle user status error:', error);
    }
  };

  const handlePasswordReset = async (userId: string) => {
    try {
      await resetUserPassword(userId);
    } catch (error) {
      console.error('Reset password error:', error);
    }
  };

  const handleSave = async (values: any) => {
    try {
      const userData: PlatformUserFormData = {
        ...values,
        status: values.status || 'active',
        platformRoles: values.platformRoles || [],
      };

      if (editingUser) {
        userData.id = editingUser.id;
        await updateUser(userData);
      } else {
        await createUser(userData);
      }
      
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('Save user error:', error);
    }
  };

  // 表格列定义
  const columns: ColumnsType<PlatformUser> = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
      render: (text: string, record: PlatformUser) => (
        <Space>
          <UserOutlined />
          <span>{text}</span>
          {record.isSuperAdmin && (
            <Tooltip title="超级管理员">
              <CrownOutlined style={{ color: '#faad14' }} />
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: '真实姓名',
      dataIndex: 'realName',
      key: 'realName',
      width: 100,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 180,
      render: (text: string) => (
        <Space>
          <MailOutlined />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
      render: (text: string) => text ? (
        <Space>
          <PhoneOutlined />
          <span>{text}</span>
        </Space>
      ) : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          active: { color: 'success', text: '正常' },
          inactive: { color: 'default', text: '禁用' },
          locked: { color: 'error', text: '锁定' },
        };
        const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.inactive;
        return <Badge status={config.color as any} text={config.text} />;
      },
    },
    {
      title: '角色',
      dataIndex: 'platformRoles',
      key: 'platformRoles',
      width: 150,
      render: (roles: string[]) => (
        <Space wrap>
          {roles?.map((role, index) => (
            <Tag key={index} color="blue">
              {role}
            </Tag>
          )) || '-'}
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (text: string) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 220,
      fixed: 'right',
      render: (_, record: PlatformUser) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{ color: '#1890ff' }}
          >
            详情
          </Button>
          
          {checkAnyPermission(['platform:user:update']) && (
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{ color: '#52c41a' }}
            >
              编辑
            </Button>
          )}
          {!checkAnyPermission(['platform:user:update']) && (
            <Button
              type="text"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
              style={{ color: '#52c41a' }}
              disabled
            >
              编辑
            </Button>
          )}

          {checkAnyPermission(['platform:user:status']) && (
            record.status === 'active' ? (
              <Popconfirm
                title="确定要锁定该用户吗？"
                onConfirm={() => handleStatusToggle(record.id, 'locked')}
              >
                <Button
                  type="text"
                  size="small"
                  icon={<LockOutlined />}
                  danger
                >
                  锁定
                </Button>
              </Popconfirm>
            ) : (
              <Popconfirm
                title="确定要启用该用户吗？"
                onConfirm={() => handleStatusToggle(record.id, 'active')}
              >
                <Button
                  type="text"
                  size="small"
                  icon={<UnlockOutlined />}
                  style={{ color: '#52c41a' }}
                >
                  启用
                </Button>
              </Popconfirm>
            )
          )}

          {checkAnyPermission(['platform:user:password']) && (
            <Popconfirm
              title="确定要重置该用户的密码吗？"
              onConfirm={() => handlePasswordReset(record.id)}
            >
              <Button
                type="text"
                size="small"
                icon={<SafetyOutlined />}
              >
                重置密码
              </Button>
            </Popconfirm>
          )}

          {!record.isSuperAdmin && (
            <Popconfirm
              title="确定要删除该用户吗？"
              onConfirm={() => handleDelete([record.id])}
            >
              <Button
                type="text"
                size="small"
                icon={<DeleteOutlined />}
                danger
                disabled={!checkAnyPermission(['platform:user:delete'])}
              >
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题与操作区（统一样式） */}
      <div
        style={{
          marginBottom: 24,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '0 4px',
        }}
      >
        <div>
          <Title level={4} style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
            <TeamOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            平台用户管理
          </Title>
          <Text type="secondary" style={{ fontSize: 14, marginTop: 4, display: 'block' }}>
            管理平台用户及角色分配
          </Text>
        </div>
        <Space>
          <Search
            placeholder="搜索用户名、姓名、邮箱"
            allowClear
            style={{ width: 300 }}
            onSearch={handleSearch}
            defaultValue={searchText}
          />
          <Select
            placeholder="状态筛选"
            style={{ width: 140 }}
            allowClear
            value={statusFilter}
            onChange={handleStatusFilter}
          >
            <Option value="all">全部</Option>
            <Option value="active">正常</Option>
            <Option value="inactive">禁用</Option>
            <Option value="locked">锁定</Option>
          </Select>
          <Button
            icon={<ReloadOutlined />}
            onClick={refresh}
            style={{ borderColor: '#d9d9d9', color: '#666' }}
          >
            刷新
          </Button>
          {checkAnyPermission(['platform:user:create']) && (
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增用户
            </Button>
          )}
        </Space>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={users}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: handlePageChange,
            onShowSizeChange: handlePageChange,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 用户编辑/新增模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { min: 3, max: 20, message: '用户名长度为3-20个字符' },
                  ({ getFieldValue }) => ({
                    async validator(_, value) {
                      if (!value) return Promise.resolve();
                      try {
                        const res = await platformUsersApi.checkUsernameExists(value, editingUser?.id);
                        if (res.exists) {
                          return Promise.reject(new Error('该用户名已被占用'));
                        }
                        return Promise.resolve();
                      } catch (e) {
                        return Promise.resolve();
                      }
                    }
                  })
                ]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="realName"
                label="真实姓名"
                rules={[{ required: true, message: '请输入真实姓名' }]}
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                  ({ getFieldValue }) => ({
                    async validator(_, value) {
                      if (!value) return Promise.resolve();
                      try {
                        const res = await platformUsersApi.checkEmailExists(value, editingUser?.id);
                        if (res.exists) {
                          return Promise.reject(new Error('该邮箱已被占用'));
                        }
                        return Promise.resolve();
                      } catch (e) {
                        return Promise.resolve();
                      }
                    }
                  })
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
                ]}
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="avatar"
                label="头像地址"
                rules={[{ type: 'url', message: '请输入有效的URL地址' }]}
              >
                <Input placeholder="请输入头像图片URL" />
              </Form.Item>
            </Col>
          </Row>

          {!editingUser && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { min: 6, message: '密码至少6位' },
                  ]}
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="confirmPassword"
                  label="确认密码"
                  dependencies={['password']}
                  rules={[
                    { required: true, message: '请确认密码' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('两次输入的密码不一致'));
                      },
                    }),
                  ]}
                >
                  <Input.Password placeholder="请再次输入密码" />
                </Form.Item>
              </Col>
            </Row>
          )}

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                initialValue="active"
              >
                <Select>
                  <Option value="active">正常</Option>
                  <Option value="inactive">禁用</Option>
                  <Option value="locked">锁定</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="platformRoles"
                label="角色"
              >
                <Select
                  mode="multiple"
                  placeholder="请选择角色"
                  options={availableRoles.map(role => ({
                    label: role.name || role.roleName,
                    value: role.code || role.roleCode,
                  }))}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={3} placeholder="请输入备注信息" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
              <Button onClick={() => {
                setModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 用户详情模态框 */}
      <Modal
        title="用户详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {viewingUser && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="用户名">
              <Space>
                <UserOutlined />
                {viewingUser.username}
                {viewingUser.isSuperAdmin && (
                  <Tag color="gold" icon={<CrownOutlined />}>
                    超级管理员
                  </Tag>
                )}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="真实姓名">
              {viewingUser.realName}
            </Descriptions.Item>
            <Descriptions.Item label="邮箱">
              <Space>
                <MailOutlined />
                {viewingUser.email}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="手机号">
              {viewingUser.phone ? (
                <Space>
                  <PhoneOutlined />
                  {viewingUser.phone}
                </Space>
              ) : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              {(() => {
                const statusConfig = {
                  active: { color: 'success', text: '正常' },
                  inactive: { color: 'default', text: '禁用' },
                  locked: { color: 'error', text: '锁定' },
                };
                const config = statusConfig[viewingUser.status as keyof typeof statusConfig] || statusConfig.inactive;
                return <Badge status={config.color as any} text={config.text} />;
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="角色">
              <Space wrap>
                {viewingUser.platformRoles?.map((role, index) => (
                  <Tag key={index} color="blue">
                    {role}
                  </Tag>
                )) || '-'}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              <Space>
                <CalendarOutlined />
                {viewingUser.createTime ? dayjs(viewingUser.createTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              <Space>
                <ClockCircleOutlined />
                {viewingUser.updateTime ? dayjs(viewingUser.updateTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="备注" span={2}>
               {(viewingUser as any).remark || '-'}
             </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default PlatformUsersPage;